<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float: right"
          type="primary"
          size="small"
          @click="search"
        >
          查询搜索
        </el-button>
        <el-button style="float: right; margin-right: 15px" size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form
          :inline="true"
          :model="listQuery"
          size="small"
          label-width="140px"
        >
          <el-form-item label="输入搜索：">
            <el-input
              v-model="listQuery.orderId"
              class="input-width"
              placeholder="订单编号"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号码:">
            <el-input
              v-model="listQuery.phoneNumber"
              class="input-width"
              placeholder="收货人手机号码"
            ></el-input>
          </el-form-item>
          <el-form-item label="提交时间：">
            <el-date-picker
              v-model="value2"
              type="datetimerange"
              align="right"
              start-placeholder="开始日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              end-placeholder="结束日期"
              :default-time="['12:00:00', '08:00:00']"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="订单状态：">
            <el-select
              v-model="listQuery.orderStatus"
              class="input-width"
              placeholder="全部"
              clearable
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="订单分类：">
            <el-select
              v-model="listQuery.orderType"
              class="input-width"
              placeholder="全部"
              clearable
            >
              <el-option
                v-for="item in orderTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
    </el-card>
    <div class="table-container">
      <el-table
        ref="orderTable"
        :data="list"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="listLoading"
        border
      >
        <el-table-column
          type="selection"
          width="60"
          align="center"
        ></el-table-column>
        <el-table-column type="index" label="编号" width="80" align="center">
          <!-- <template slot-scope="scope">{{ scope.row.orderId }}</template> -->
        </el-table-column>
        <el-table-column label="订单编号" width="180" align="center">
          <template slot-scope="scope">{{ scope.row.orderId }} </template>
        </el-table-column>
        <el-table-column label="提交时间" width="180" align="center">
          <template slot-scope="scope">{{ scope.row.createTime }}</template>
        </el-table-column>
        <el-table-column label="用户账号" align="center">
          <template slot-scope="scope">{{ scope.row.userId }}</template>
        </el-table-column>
        <el-table-column label="订单金额" width="120" align="center">
          <template slot-scope="scope">￥{{ scope.row.payment }}</template>
        </el-table-column>
        <el-table-column label="订单类型" width="120" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.addressId == '余额充值' ? 'success' : 'warning'"
              effect="dark"
            >
              {{ scope.row.addressId == "余额充值" ? "余额充值" : "购书订单" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" width="120" align="center">
          <template slot-scope="scope">
            <svg class="icon" aria-hidden="true" >
              <use xlink:href="#icon-zhifu-yue" v-if='scope.row.paymentType==3'></use>
               <use xlink:href="#icon-weixin" v-if='scope.row.paymentType==0'></use>
                <use xlink:href="#icon-zhifupingtai-zhifubao-copy" v-if='scope.row.paymentType==1'></use>
            </svg>
           <i v-if='scope.row.paymentType==-1'>无支付方式</i>
          </template>
        </el-table-column>

        <el-table-column label="订单状态" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | formatStatu" effect="dark">
              {{ scope.row.status | formatStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleViewOrder(scope.$index, scope.row.orderId)"
              >查看订单</el-button
            >
            <el-button
              size="mini"
              @click="handleCloseOrder(scope.$index, scope.row)"
              v-show="scope.row.status == 0"
              type="danger"
              plain
              >关闭订单</el-button
            >
            <el-button
              size="mini"
              type="info"
              plain
              @click="handleDeliveryOrder(scope.$index, scope.row)"
              v-show="scope.row.status == 1"
              >订单发货</el-button
            >
            <el-button
              size="mini"
              type="success"
              plain
              @click="handleViewLogistics(scope.$index, scope.row)"
              v-show="scope.row.status == 2 || scope.row.status == 3"
              >订单跟踪</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDeleteOrder(scope.$index, scope.row)"
              v-show="scope.row.status === -1"
              >删除订单</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="batch-operate-container">
      <el-select size="small" v-model="operateType" placeholder="批量操作">
        <el-option
          v-for="item in operateOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button
        style="margin-left: 20px"
        class="search-button"
        @click="handleBatchOperate()"
        type="primary"
        size="small"
      >
        确定
      </el-button>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :layout="width > 1100 ? 'total, sizes, prev, pager, next, jumper' : 'total, prev, pager, next'"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[5, 10, 15]"
        :total="total"
         pager-count="5"
      >
      </el-pagination>
    </div>
    <!-- <el-dialog
      title="关闭订单"
      :visible.sync="closeOrder.dialogVisible" width="30%">
      <span style="vertical-align: top">操作备注：</span>
      <el-input
        style="width: 80%"
        type="textarea"
        :rows="5"
        placeholder="请输入内容"
        v-model="closeOrder.content">
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeOrder.dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCloseOrderConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <logistics-dialog v-model="logisticsDialogVisible"></logistics-dialog> -->
  </div>
</template>
<script>
import { fetchList, sendOrder, deleteOrder } from "@/api/order";
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  orderSn: null,
  receiverKeyword: null,
  status: null,
  orderType: null,
  sourceType: null,
  endTime: null,
  startTime: null,
  orderId: null,
  phoneNumber: null,
};
export default {
  name: "orderList",
  // components:{LogisticsDialog},
  data() {
    return {
      width: "",
      loading: true,
      listQuery: Object.assign({}, defaultListQuery),
      listLoading: true,
      list: null,
      total: null,
      value2: "",
      pageNum: 1,
      pageSize: 10,
      operateType: null,
      multipleSelection: [],
      closeOrder: {
        dialogVisible: false,
        content: null,
        orderIds: [],
      },
      statusOptions: [
        {
          label: "待付款",
          value: 0,
        },
        {
          label: "待发货",
          value: 1,
        },
        {
          label: "已发货",
          value: 2,
        },
        {
          label: "已完成",
          value: 3,
        },
        {
          label: "已关闭",
          value: -1,
        },
      ],
      orderTypeOptions: [
        {
          label: "购书订单",
          value: 1,
        },
        {
          label: "充值订单",
          value: 2,
        },
      ],
      sourceTypeOptions: [
        {
          label: "PC订单",
          value: 0,
        },
        {
          label: "APP订单",
          value: 1,
        },
      ],
      operateOptions: [
        {
          label: "批量发货",
          value: 1,
        },
        {
          label: "关闭订单",
          value: 2,
        },
        {
          label: "删除订单",
          value: 3,
        },
      ],
      logisticsDialogVisible: false,
    };
  },
  //获取屏幕宽度
  mounted() {
    this.width = document.body.clientWidth;
   
  },
  created() {
    this.getList(1, 10, 1);
  },
  filters: {
    formatCreateTime(time) {
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
    formatPayType(value) {
      if (value === 1) {
        return "支付宝";
      } else if (value === 2) {
        return "微信";
      } else {
        return "未支付";
      }
    },
    formatSourceType(value) {
      if (value === 1) {
        return "APP订单";
      } else {
        return "PC订单";
      }
    },
    formatStatus(value) {
      if (value === 1) {
        return "待发货";
      } else if (value === 2) {
        return "已发货";
      } else if (value === 3) {
        return "已完成";
      } else if (value === -1) {
        return "已关闭";
      } else if (value === 5) {
        return "无效订单";
      } else {
        return "待付款";
      }
    },
    formatStatu(value) {
      if (value === 1) {
        return "info";
      } else if (value === 2) {
        return "";
      } else if (value === 3) {
        return "success";
      } else if (value === -1) {
        return "warning";
      } else if (value === 5) {
        return "无效订单";
      } else {
        return "danger";
      }
    },
  },
  methods: {
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList(this.pageNum, this.pageSize);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleViewOrder(index, row) {
      this.$router.push({ path: "/orders/orderDetail", query: { id: row } });
    },
    handleCloseOrder(index, row) {
      this.closeOrder.dialogVisible = true;
      this.closeOrder.orderIds = [row.id];
    },
    handleDeliveryOrder(index, row) {
      this.$confirm("是否确定该订单已发货?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let arr = [];
          arr.push(row.orderId);
          let params = new URLSearchParams();
          params.append("batchIds", arr);
          sendOrder(params).then((res) => {
            this.$message.success("发货成功");
            console.log(res);
            this.getList(this.pageNum, this.pageSize);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消发货",
          });
        });
    },
    handleViewLogistics(index, row) {
      this.logisticsDialogVisible = true;
    },
    handleDeleteOrder(index, row) {
      let ids = [];
      console.log(row);
      ids.push(row.orderId);
      console.log(ids);
      this.deleteOrder(ids);
    },
    handleBatchOperate() {
      if (this.multipleSelection == null || this.multipleSelection.length < 1) {
        this.$message({
          message: "请选择要操作的订单",
          type: "warning",
          duration: 1000,
        });
        return;
      }
      if (this.operateType === 1) {
        //批量发货
        let list = [];
        console.log(this.multipleSelection);
        for (let i = 0; i < this.multipleSelection.length; i++) {
          if (this.multipleSelection[i].status === 1) {
            list.push(this.multipleSelection[i].orderId);
          }
        }
        if (list.length === 0) {
          this.$message({
            message: "选中订单中没有可以发货的订单",
            type: "warning",
            duration: 1000,
          });
          return;
        } else {
          console.log(list);
          let params = new URLSearchParams();
          params.append("batchIds", list);
          sendOrder(params).then((res) => {
            this.$message.success("发货成功");
            console.log(res);
            this.getList(this.pageNum, this.pageSize);
          });
        }
      } else if (this.operateType === 2) {
        //关闭订单
        this.closeOrder.orderIds = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.closeOrder.orderIds.push(this.multipleSelection[i].id);
        }
        this.closeOrder.dialogVisible = true;
      } else if (this.operateType === 3) {
        //删除订单
        let ids = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
          if (this.multipleSelection[i].status === -1) {
            ids.push(this.multipleSelection[i].orderId);
          }
        }
        if (ids.length === 0) {
          this.$message({
            message: "选中订单中没有可以删除的订单",
            type: "warning",
            duration: 1000,
          });
          return;
        } else {
          this.deleteOrder(ids);
        }
      }
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      console.log(this.listQuery.pageSize);
     this.getList(this.pageNum, this.pageSize);
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      console.log(this.pageNum, this.pageSize);
     this.getList(this.pageNum, this.pageSize);
    },
    handleCloseOrderConfirm() {
      if (this.closeOrder.content == null || this.closeOrder.content === "") {
        this.$message({
          message: "操作备注不能为空",
          type: "warning",
          duration: 1000,
        });
        return;
      }
      let params = new URLSearchParams();
      params.append("ids", this.closeOrder.orderIds);
      params.append("note", this.closeOrder.content);
      closeOrder(params).then((response) => {
        this.closeOrder.orderIds = [];
        this.closeOrder.dialogVisible = false;
        this.getList(this.pageNum, this.pageSize);
        this.$message({
          message: "修改成功",
          type: "success",
          duration: 1000,
        });
      });
    },
    search() {
    this.getList(this.pageNum, this.pageSize);
      console.log(this.value2);
    },
    getList(page, pageSize) {
      console.log(this.listQuery);
      this.listLoading = true;
      fetchList({
        page: this.listQuery.pageNum,
        pageSize: this.listQuery.pageSize,
        endTime: this.value2[1],
        startTime: this.value2[0],
        orderStatus: this.listQuery.orderStatus,
        orderType: this.listQuery.orderType,
        orderId: this.listQuery.orderId,
        phoneNumber: this.listQuery.phoneNumber,
      })
        .then((response) => {
          console.log(response);
          this.listLoading = false;
          this.list = response.data.data.records;
          console.log(this.list);
          this.total = response.data.data.total;
        })
        .catch((error) => {
          this.listLoading = false;
          this.$message({
            message: "获取订单列表失败",
            type: "error",
            duration: 1000,
          });
        });
    },
    deleteOrder(ids) {
      this.$confirm("是否要进行该删除操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let params = new URLSearchParams();
        params.append("batchIds", ids);
        deleteOrder(params).then((response) => {
          this.$message({
            message: "删除成功！",
            type: "success",
            duration: 1000,
          });
          this.getList(this.pageNum, this.pageSize);
        });
      });
    },
    covertOrder(order) {
      let address =
        order.receiverProvince +
        order.receiverCity +
        order.receiverRegion +
        order.receiverDetailAddress;
      let listItem = {
        orderId: order.id,
        orderSn: order.orderSn,
        receiverName: order.receiverName,
        receiverPhone: order.receiverPhone,
        receiverPostCode: order.receiverPostCode,
        address: address,
        deliveryCompany: null,
        deliverySn: null,
      };
      return listItem;
    },
  },
};
</script>
<style scoped>
.input-width {
  width: 203px;
}
.filter-container {
  margin-bottom: 20px;
}
.table-container {
  margin-top: 20px;
}
.batch-operate-container {
  margin-top: 20px;
  float: left;
}
.el-pagination {
  margin-top: 20px;
  float: right;
}
svg{
  width: 2em;
  height: 2em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>
